<?php

namespace App\Http\Controllers\Admin\AirLine\Base;

use App\Exports\ContainerExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\airline\base\ContainerRequest;
use App\Imports\ContainerImport;
use App\Models\airline\base\CodeDetailModel;
use App\Models\airline\base\CodeModel;
use App\Models\airline\base\ContainerModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class Container extends Controller
{
    use ContainerRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $container_id = $request->input('container_id', '');
        $code = $request->input('code', '');
        $status = $request->input('status', '');
        $vehicle = $request->input('vehicle', '');
        $get_start = $request->input('get_start', '');
        $get_end = $request->input('get_end', '');
        $use_start = $request->input('use_start', '');
        $use_end = $request->input('use_end', '');

        $query = ContainerModel::query()->with(['create_admin', 'code']);

        if($container_id){
            $container_id = explode(',', $container_id);
            $query = $query->whereIn('container_id', $container_id);
        }

//        if($code || ($get_start && $get_end)){
//            $code_id = [];
//            if($code){
//                $code = explode(',', $code);
//                $code_id = CodeModel::whereIn('code', $code)->pluck('id');
//            }
//            if($get_start && $get_end){
//                $code_id2 = CodeModel::whereBetween('get_time', [$get_start, $get_end])->pluck('id');
//                $code_id = array_intersect($code_id, $code_id2);
//            }
//
//            $query = $query->whereIn('code_id', $code_id);
//        }

        if($status != ''){
            $query = $query->where('status', $status);
        }

        if($vehicle){
            $query = $query->where('vehicle', $vehicle);
        }

        if($use_start && $use_end){
            $query = $query->whereBetween('use_time', [$use_start, $use_end]);
        }

        if($get_start && $get_end){
            $query = $query->whereBetween('take_time', [$get_start, $get_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'container_id' => $item->container_id,
//                'ban_id' => $item->ban_id,
                'vehicle' => $item->vehicle,
//                'ban_name' => $item->ban ? $item->ban->name : '',
//                'ban_length' => $item->ban ? $item->ban->length : '',
//                'ban_width' => $item->ban ? $item->ban->width : '',
//                'ban_height' => $item->ban ? $item->ban->height : '',
//                'ban_volume' => $item->ban ? $item->ban->volume : '',
//                'ban_limit_weight' => $item->ban ? $item->ban->limit_weight : '',
//                'ban_pivot' => $item->ban ? $item->ban->pivot : '',
                'code_id' => $item->code_id,
                'code' => $item->code ? $item->code->code : '',
                'code_take_time' => $item->code ? $item->code->take_time : '',
                'status' => $item->status,
                'status_text' => ContainerModel::STATUS[$item->status],
                'use_time' => $item->use_time,
                'take_time' => $item->take_time,
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin ? $item->create_admin->staff->name: '',
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = new ContainerModel();
        $data = [];
        foreach ($params['container_id'] as $container_id) {
            $find = (new ContainerModel())->where('container_id', $container_id)->where('status', 0)->first();

            if($find){
                return $this->error('ID-' . $container_id . '已存在');
            }

//            $find_code = CodeModel::where('id', $params['code_id'])->first();
            $find_code = CodeDetailModel::where('code_id', $params['code_id'])->where('name', $params['vehicle'])->first();

            if($find_code->used + 1 > $find_code->number){
                return $this->error('载具数量不足');
            }else{
                $find_code->used += 1;
                $find_code->save();
            }

            $this_data = [
                'code_id' => $params['code_id'],
                'vehicle' => $params['vehicle'],
                'status' => $params['status'] ?? 0,
                'container_id' => $container_id,
                'created_admin_id' => $auth->id,
                'created_at' => date('Y-m-d H:i:s', time()),
            ];

            if(isset($params['use_time']) && $params['use_time']){
                $this_data['use_time'] = $params['use_time'];
            }

            if(isset($params['take_time']) && $params['take_time']){
                $this_data['take_time'] = $params['take_time'];
            }

            $data[] = $this_data;
        }

        $model->insert($data);

        return $this->success();
    }

    public function update(Request $request, $id){
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = ContainerModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        if($params['container_id'] != $model->container_id){
            $find = ContainerModel::where('container_id', $params['container_id'])->where('status', 0)->first();
            if($find){
                return $this->error('集装器ID已存在');
            }
        }

        $model->code_id = $params['code_id'];
        $model->vehicle = $params['vehicle'];
        $model->status = $params['status'] ?? 0;
        $model->container_id = $params['container_id'];

        if(isset($params['use_time']) && $params['use_time']){
            $model->use_time = $params['use_time'];
        }

        if(isset($params['take_time']) && $params['take_time']){
            $model->take_time = $params['take_time'];
        }

        $model->save();

        return $this->success();
    }


    public function delete(int $id){
        $model = ContainerModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }

        if($model->status == 1){
            return $this->error('已使用，不能删除');
        }else{
            $code = CodeDetailModel::where('code_id', $model->code_id)->where('name', $model->vehicle)->first();
            if($code){
                $code->used -= 1;
                $code->save();
            }

        }

        $model->delete();
        return $this->success();
    }


    public function select()
    {
        $list = ContainerModel::select('id', 'container_id', 'vehicle')->get()->toArray();
        return $this->success($list);
    }

    public function export(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = ContainerModel::with('code');
        $query->whereIn('id', $ids);
        $items = $query
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {


            $res = [
                'container_id' => $item->container_id,
                'code' => $item->code->code ?? '',
                'vehicle' => $item->vehicle,
            ];

            return $res;
        });

        $file_name = '集装器导出-'.date('Ymd').'.xlsx';

        return Excel::download(new ContainerExport($list), $file_name);
    }

    public function import(Request $request)
    {
        $auth = $request->get('auth');
        $file = $request->file('file');
        if(!$file) {
            return $this->error('请选择文件');
        }

        $import = new ContainerImport();
        Excel::import($import, $file);


        $res = $import->get_result();

        if(isset($res->error) && $res->error){
            return $this->error(implode(',', $res->error));
        }

        $lines = $res->lines;

        DB::beginTransaction();
        try {
            foreach ($lines as $line){
                $container = new ContainerModel();
                $container->container_id = $line['container_id'];
                $container->code_id = $line['code_id'];
                $container->vehicle = $line['vehicle'];
                $container->created_admin_id = $auth->id;
                $container->save();

                if($line['code_id'] && $line['vehicle']){
                    $code = CodeDetailModel::where('code_id', $line['code_id'])->where('name', $line['vehicle'])->first();
                    if(!$code){
                        return $this->error('载具不存在');
                    }
                    if($code->used + 1 > $code->number){
                        return $this->error('载具数量不足');
                    }
                    $code->used += 1;
                    $code->save();
                }
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }

}
